from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType

from zope.component import getAdapters

import transaction

def createFolderStructure(portal):
    """Define which objects we want to create in the site.
    """
    #profile_children is used to create folder structure. Not necessary in this case.
    profile_sub_children = [
        {   'id': '', 
            'title': '', 
            'description': '',
            'type': '',
            'excludeFromNav': True,
            'layout': '',
            'language':False,  
            },                  
            ]
    profile_children = [
         {  'id': '', 
            'title': '',
            'description': '',
            'type': '',
            'layout': '',
            'language':False,  
            'excludeFromNav': True,
            'children': profile_sub_children,
            },                  
        ]    
    top_objects = [
       
        {   'id': 'micetal', 
            'title': 'Micetal',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_micetal_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },
        {   'id': 'copalia', 
            'title': 'Copalia',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_copalia_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },    
        {   'id': 'rupafin', 
            'title': 'Rupafin',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_rupafin_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },    
        {   'id': 'silostar', 
            'title': 'Silostar',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_silostar_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },    
        {   'id': 'disgren', 
            'title': 'Disgren',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_disgren_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },    
        {   'id': 'telo', 
            'title': 'Telo',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_telo_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },    
        {   'id': 'ferinject', 
            'title': 'Ferinject',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_ferinject_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },    
        {   'id': 'caphosol', 
            'title': 'Caphosol',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_caphosol_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },      
        {   'id': 'alvesco', 
            'title': 'Alvesco',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_alvesco_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },
        {   'id': 'vimovo', 
            'title': 'Vimovo',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_vimovo_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },
        {   'id': 'palladone', 
            'title': 'Palladone',
            'description': '',
            'type': 'Folder',
            'layout': 'uriach_palladone_view',
            'language':False,  
            'excludeFromNav': True,
            'children': '',
            },                              
        ]

    createObjects(parent=portal, children=top_objects)
   

def createObjects(parent, children, obj_lg=None):
    """This will create new objects, or modify existing ones if id's and type
    match.
    """
    ltool = getToolByName(parent, 'portal_languages')
    langs = ltool.listSupportedLanguages()
    lg_codes = ",".join(str(lang[0]) for lang in langs).split(',')
    
    #parent.plone_log("Creating %s in %s" % (children, parent))
    existing = parent.objectIds()
    #parent.plone_log("Existing ids: %s" % existing)
    
            
    for new_object in children:
        if new_object['language']:
            for code in lg_codes:
                obj_id = new_object['id']+'-'+code
                if obj_id in existing:
                    parent.plone_log("%s exists, skipping" % obj_id)
                else:
                  created =  _createObjectByType(new_object['type'], parent, \
                        id=obj_id, title=new_object['title'], \
                        description=new_object['description'])
                parent.plone_log("Now to modify the new_object...")
                obj = parent.get(obj_id, None)
                if obj is None:
                    parent.plone_log("can't get new_object %s to modify it!" % obj_id)
                else:
                    #import pdb;pdb.set_trace()
                    obj.setExcludeFromNav(new_object['excludeFromNav'])
                    obj.reindexObject()
                    if obj.Type() != new_object['type']:
                        
                        obj.setLanguage(code)                 
                        parent.plone_log("types don't match! ["+ obj.Type() + "] is not equal to ["+new_object['type']+"]")
                    else:                
                        
                        obj.setLanguage(code)
                        if new_object['layout']:
                            obj.setLayout(new_object['layout'])
                            obj.reindexObject()
                        children = new_object.get('children',[])
                        if len(children) > 0:
                            createObjects(obj, children, code)
        else:
            #import pdb;pdb.set_trace()
            if obj_lg is None:
                obj_lg=ltool.getPreferredLanguage()
                
            if new_object['id'] in existing:
                parent.plone_log("%s exists, skipping" % new_object['id'])
            else:
                _createObjectByType(new_object['type'], parent, \
                    id=new_object['id'], title=new_object['title'], \
                    description=new_object['description'])
            parent.plone_log("Now to modify the new_object...")
            obj = parent.get(new_object['id'], None)
            if obj is None:
                parent.plone_log("can't get new_object %s to modify it!" % new_object['id'])
            else:
                #import pdb;pdb.set_trace()
                obj.setExcludeFromNav(new_object['excludeFromNav'])
                obj.reindexObject()
                if obj.Type() != new_object['type']:
                    obj.setLanguage(obj_lg)                 
                    parent.plone_log("types don't match! ["+ obj.Type() + "] is not equal to ["+new_object['type']+"]")
                else:                
                    obj.setLanguage(obj_lg)
                    if new_object['layout']:
                        obj.setLayout(new_object['layout'])
                        obj.reindexObject()
                    children = new_object.get('children',[])
                    if len(children) > 0:
                        createObjects(obj, children, obj_lg)

def setupVarious(context):
    
    # Ordinarily, GenericSetup handlers check for the existence of XML files.
    # Here, we are not parsing an XML file, but we use this text file as a 
    # flag to check that we actually meant for this import step to be run.
    # The file is found in profiles/default.
    
    
    portal = context.getSite()
    
    if context.readDataFile('uriachpharma.theme_various.txt') is None:
        return

    createFolderStructure(portal)
    transaction.commit()
      